import codecs
import logging
import logging.config
import re
from pathlib import Path

from utils.tools import get_config_path


def setup_logging():
    ini_file = r"../logs/logging.ini"
    ini_file = get_config_path(ini_file)
    mkdir_path = get_config_path(r"../logs")
    Path(mkdir_path).mkdir(exist_ok=True)
    # 关键修改：用 UTF-8 编码打开配置文件

    modify_log_path(ini_file)
    with codecs.open(ini_file, 'r', encoding='utf-8') as f:
        logging.config.fileConfig(f, disable_existing_loggers=False)

    return logging.getLogger()


def modify_log_path(config_file):
    # 逐行检查并修改
    with open(config_file, 'r', encoding='utf-8') as f:
        lines = f.readlines()
    with codecs.open(config_file, 'w', encoding='utf-8') as f:
        for line in lines:
            # 检查是否是 args 行
            if line.strip().startswith('args ='):
                # 使用正则替换第一个参数（路径部分）
                # 提取原始文件名（如从"../logs/net_deal.log"中获取"net_deal.log"）
                match = re.search(r'args = \("([^"]+)"', line)
                if match:
                    original_path = match.group(1)
                    new_path = get_config_path(original_path)
                    print(new_path)
                    # 替换行中的路径
                    line = line.replace(original_path, new_path)
                    line = line.replace('\\', '/')
            f.write(line)


if __name__ == '__main__':
    setup_logging()
